[[...path]].page.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import React from 'react';
  2. import { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  11. import { MainPane } from '~/components/Layout/MainPane';
  12. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  13. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  14. import { Page } from '~/components/Page';
  15. import type { PageSideContentsProps } from '~/components/PageSideContents';
  16. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  17. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  18. import { CrowiRequest } from '~/interfaces/crowi-request';
  19. import { RendererConfig } from '~/interfaces/services/renderer';
  20. import { IShareLinkHasId } from '~/interfaces/share-link';
  21. import type { PageDocument } from '~/server/models/page';
  22. import {
  23. useCurrentUser, useCurrentPageId, useRendererConfig, useIsSearchPage, useCurrentPathname,
  24. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useDrawioUri, useIsContainerFluid,
  25. } from '~/stores/context';
  26. import loggerFactory from '~/utils/logger';
  27. import { NextPageWithLayout } from '../_app.page';
  28. import {
  29. CommonProps, getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig,
  30. } from '../utils/commons';
  31. const logger = loggerFactory('growi:next-page:share');
  32. const PageSideContents = dynamic<PageSideContentsProps>(() => import('~/components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  33. // const Comments = dynamic(() => import('~/components/Comments').then(mod => mod.Comments), { ssr: false });
  34. const ShareLinkAlert = dynamic(() => import('~/components/Page/ShareLinkAlert'), { ssr: false });
  35. const ForbiddenPage = dynamic(() => import('~/components/ForbiddenPage'), { ssr: false });
  36. type Props = CommonProps & {
  37. shareLinkRelatedPage?: IShareLinkRelatedPage,
  38. shareLink?: IShareLinkHasId,
  39. isExpired: boolean,
  40. disableLinkSharing: boolean,
  41. isSearchServiceConfigured: boolean,
  42. isSearchServiceReachable: boolean,
  43. isSearchScopeChildrenAsDefault: boolean,
  44. drawioUri: string | null,
  45. rendererConfig: RendererConfig,
  46. };
  47. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  48. superjson.registerCustom<IShareLinkRelatedPage, string>(
  49. {
  50. isApplicable: (v): v is IShareLinkRelatedPage => {
  51. return v != null
  52. && v.toObject != null
  53. && v.lastUpdateUser != null
  54. && v.creator != null
  55. && v.revision != null;
  56. },
  57. serialize: (v) => { return superjson.stringify(v.toObject()) },
  58. deserialize: (v) => { return superjson.parse(v) },
  59. },
  60. 'IShareLinkRelatedPageTransformer',
  61. );
  62. // GrowiContextualSubNavigation for shared page
  63. // get page info from props not to send request 'GET /page' from client
  64. type GrowiContextualSubNavigationForSharedPageProps = {
  65. currentPage?: IPagePopulatedToShowRevision,
  66. isLinkSharingDisabled: boolean,
  67. }
  68. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  69. const { currentPage, isLinkSharingDisabled } = props;
  70. if (currentPage == null) { return <></> }
  71. return (
  72. <div data-testid="grw-contextual-sub-nav">
  73. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  74. </div>
  75. );
  76. };
  77. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  78. useCurrentPathname(props.shareLink?.relatedPage.path);
  79. useIsSearchPage(false);
  80. useShareLinkId(props.shareLink?._id);
  81. useCurrentPageId(props.shareLink?.relatedPage._id);
  82. useCurrentUser(props.currentUser);
  83. useRendererConfig(props.rendererConfig);
  84. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  85. useIsSearchServiceReachable(props.isSearchServiceReachable);
  86. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  87. useDrawioUri(props.drawioUri);
  88. useIsContainerFluid(props.isContainerFluid);
  89. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  90. const isNotFound = props.shareLink == null || props.shareLink.relatedPage == null || props.shareLink.relatedPage.isEmpty;
  91. const isShowSharedPage = !props.disableLinkSharing && !isNotFound && !props.isExpired;
  92. const shareLink = props.shareLink;
  93. const title = generateCustomTitleForPage(props, props.shareLinkRelatedPage?.path ?? '');
  94. const sideContents = shareLink != null
  95. ? <PageSideContents page={shareLink.relatedPage} />
  96. : <></>;
  97. // const footerContents = shareLink != null && isPopulated(shareLink.relatedPage.revision)
  98. // ? (
  99. // <>
  100. // <Comments pageId={shareLink._id} pagePath={shareLink.relatedPage.path} revision={shareLink.relatedPage.revision} />
  101. // </>
  102. // )
  103. // : <></>;
  104. return (
  105. <>
  106. <Head>
  107. <title>{title}</title>
  108. </Head>
  109. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  110. <header className="py-0 position-relative">
  111. {isShowSharedPage
  112. && <GrowiContextualSubNavigationForSharedPage currentPage={props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />}
  113. </header>
  114. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  115. <MainPane
  116. sideContents={sideContents}
  117. // footerContents={footerContents}
  118. >
  119. { props.disableLinkSharing && (
  120. <div className="mt-4">
  121. <ForbiddenPage isLinkSharingDisabled={props.disableLinkSharing} />
  122. </div>
  123. )}
  124. { (isNotFound && !props.disableLinkSharing) && (
  125. <div className="container-lg">
  126. <h2 className="text-muted mt-4">
  127. <i className="icon-ban" aria-hidden="true" />
  128. <span> Page is not found</span>
  129. </h2>
  130. </div>
  131. )}
  132. { (props.isExpired && !props.disableLinkSharing && shareLink != null) && (
  133. <div className="container-lg">
  134. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  135. <h2 className="text-muted mt-4">
  136. <i className="icon-ban" aria-hidden="true" />
  137. <span> Page is expired</span>
  138. </h2>
  139. </div>
  140. )}
  141. {(isShowSharedPage && shareLink != null) && (
  142. <>
  143. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  144. <Page currentPage={props.shareLinkRelatedPage} />
  145. </>
  146. )}
  147. </MainPane>
  148. </div>
  149. </>
  150. );
  151. };
  152. SharedPage.getLayout = function getLayout(page) {
  153. return (
  154. <>
  155. <DrawioViewerScript />
  156. <ShareLinkLayout>{page}</ShareLinkLayout>
  157. </>
  158. );
  159. };
  160. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  161. const req: CrowiRequest = context.req as CrowiRequest;
  162. const { crowi } = req;
  163. const { configManager, searchService, xssService } = crowi;
  164. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  165. props.isSearchServiceConfigured = searchService.isConfigured;
  166. props.isSearchServiceReachable = searchService.isReachable;
  167. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  168. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  169. props.rendererConfig = {
  170. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  171. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  172. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  173. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  174. plantumlUri: process.env.PLANTUML_URI ?? null,
  175. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  176. // XSS Options
  177. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  178. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  179. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  180. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  181. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  182. };
  183. }
  184. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  185. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  186. props._nextI18Next = nextI18NextConfig._nextI18Next;
  187. }
  188. function getAction(props: Props): SupportedActionType {
  189. let action: SupportedActionType;
  190. if (props.isExpired) {
  191. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  192. }
  193. else if (props.shareLink == null) {
  194. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  195. }
  196. else {
  197. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  198. }
  199. return action;
  200. }
  201. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  202. const req: CrowiRequest = context.req as CrowiRequest;
  203. const parameters = {
  204. ip: req.ip,
  205. endpoint: req.originalUrl,
  206. action,
  207. user: req.user?._id,
  208. snapshot: {
  209. username: req.user?.username,
  210. },
  211. };
  212. await req.crowi.activityService.createActivity(parameters);
  213. }
  214. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  215. const req = context.req as CrowiRequest<IUserHasId & any>;
  216. const { crowi, params } = req;
  217. const result = await getServerSideCommonProps(context);
  218. if (!('props' in result)) {
  219. throw new Error('invalid getSSP result');
  220. }
  221. const props: Props = result.props as Props;
  222. try {
  223. const ShareLinkModel = crowi.model('ShareLink');
  224. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  225. if (shareLink != null) {
  226. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision();
  227. props.isExpired = shareLink.isExpired();
  228. props.shareLink = shareLink.toObject();
  229. }
  230. }
  231. catch (err) {
  232. logger.error(err);
  233. }
  234. injectServerConfigurations(context, props);
  235. await injectNextI18NextConfigurations(context, props);
  236. await addActivity(context, getAction(props));
  237. return {
  238. props,
  239. };
  240. };
  241. export default SharedPage;